package com.ssplayer.fragment;

import java.util.List;

import javax.crypto.AEADBadTagException;

import android.R.integer;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ssplayer.activity.MusicPlayerActivity;
import com.ssplayer.activity.R;
import com.ssplayer.adapter.MusicAdapter;
import com.ssplayer.adapter.MusicListAdapter;
import com.ssplayer.application.MyApplication;
import com.ssplayer.bean.Music;
import com.ssplayer.bean.MusicAction;
import com.ssplayer.bean.MusicMsg;
import com.ssplayer.database.DBHelper;
import com.ssplayer.utils.MediaUtils;

public class MusicFragment extends Fragment implements OnClickListener,
		OnItemClickListener, OnItemLongClickListener {

	private MyApplication myApp;
	private SharedPreferences sharedPreferences;
	private Context context;
	private List<Music> musics;
	private ListView music_list;
	private MusicAdapter musicAdapter;
	private ImageView playing_album;
	private TextView playing_title, playing_artist, playing_duration,
			button_play_pause;
	private MusicReceiver mReceiver;
	private int currentTime = 0;// 当前播放的时间
	private int currentMusic = 0;// 当前播放的音乐位置
	private int currentList = 0;// 当前播放的列表

	public MusicFragment() {
	}

	public MusicFragment(Context context, List<Music> musics) {
		this.context = context;
		this.musics = musics;
	}

	public class MusicReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			switch (action) {
			case MusicAction.UPDATE_ACTION:
				currentMusic = intent.getIntExtra("currentMusic", -1);
				setPlayingMusic(currentMusic);
				break;
			case MusicAction.MUSIC_CURRENT:
				currentTime = intent.getIntExtra("currentTime", 0);
				playing_duration.setText(String.valueOf(MediaUtils
						.formatDuration(currentTime)));
				break;
			case MusicAction.CONTROL_ACTION:
				getPlayStatus();
				break;
			default:
				break;
			}
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_music, container, false);
		myApp = (MyApplication) getActivity().getApplication();
		findAllViews(view);
		getPlayStatus();
		// 读取保存的播放记录
		getPlayingMusic();
		if (musics.size() > 0) {
			setPlayingMusic(currentMusic);
		}
		// 绑定数据
		musicAdapter = new MusicAdapter(context, musics);
		music_list.setAdapter(musicAdapter);
		music_list.setOnItemClickListener(this);
		music_list.setOnItemLongClickListener(this);
		// 注册广播
		registerMusicReceiver();
		return view;
	}

	private void findAllViews(View view) {
		music_list = (ListView) view.findViewById(R.id.music_list);
		playing_album = (ImageView) view.findViewById(R.id.playing_album);
		playing_title = (TextView) view.findViewById(R.id.playing_title);
		playing_artist = (TextView) view.findViewById(R.id.playing_artist);
		playing_duration = (TextView) view.findViewById(R.id.playing_duration);
		button_play_pause = (TextView) view
				.findViewById(R.id.button_play_pause);
		playing_album.setOnClickListener(this);
		playing_title.setOnClickListener(this);
		button_play_pause.setOnClickListener(this);

	}

	private void getPlayStatus() {
		switch (myApp.getMplay_status()) {
		case MusicMsg.STATUS_PLAYING:
			button_play_pause
					.setBackgroundResource(R.drawable.fragment_button_pause);
			break;
		default:
			button_play_pause
					.setBackgroundResource(R.drawable.fragment_button_play);
			break;
		}
	}

	private void registerMusicReceiver() {
		mReceiver = new MusicReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(MusicAction.UPDATE_ACTION);
		filter.addAction(MusicAction.MUSIC_CURRENT);
		filter.addAction(MusicAction.CONTROL_ACTION);
		context.registerReceiver(mReceiver, filter);
	}

	/**
	 * 音乐列表中每一项的单击事件
	 */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		currentMusic = position;
		Intent intent = new Intent();
		myApp.setMplay_status(MusicMsg.STATUS_PLAYING);
		intent.setAction(MusicAction.MUSIC_SERVICE);
		intent.putExtra("currentMusic", currentMusic);
		intent.putExtra("msg", MusicMsg.PLAY_MSG);
		// 启动Service
		context.startService(intent);
		// 底部显示正在播放的歌曲信息
		setPlayingMusic(currentMusic);

	}

	/**
	 * 长按显示添加到播放列表的对话框
	 */
	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		currentList = myApp.getCurrentlist();
		if (currentList == -1) {
			showAddDialog(position);
		} else {
			showAddOrDelDialog(position);
		}

		return false;
	}

	/**
	 * 显示添加音乐到列表的对话框
	 */
	private void showAddDialog(final int musicposition) {
		LayoutInflater factory = LayoutInflater.from(context);
		final View dialogview = factory.inflate(R.layout.music_list, null);
		ListView listView = (ListView) dialogview.findViewById(R.id.music_list);
		listView.setFadingEdgeLength(0);

		MusicListAdapter adapter = new MusicListAdapter(context,
				MediaUtils.getMusicLists(context), R.layout.music_to_list);
		listView.setAdapter(adapter);

		final AlertDialog dialog = new AlertDialog.Builder(context)
				.setTitle("添加到列表").setView(dialogview)// 在这里把写好的这个listview的布局加载dialog中
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				}).create();

		// dialog.setCanceledOnTouchOutside(false);// 使除了dialog以外的地方不能被点击
		dialog.show();
		listView.setOnItemClickListener(new OnItemClickListener() {// 响应listview中的item的点击事件

			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long id) {
				TextView listid_tv = (TextView) view
						.findViewById(R.id.musiclist_id);// 取得每条item中的textview控件
				int musicid = Integer.parseInt(String.valueOf(musics.get(
						musicposition).getId()));
				int listid = Integer.parseInt(listid_tv.getText().toString());
				DBHelper dbHelper = new DBHelper(context);
				boolean result = dbHelper.addMusicToList(listid, musicid);
				if (result) {
					Toast.makeText(context, "添加成功", Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(context, "歌曲已存在该列表中", Toast.LENGTH_SHORT)
							.show();
				}
				dialog.cancel();
			}
		});
	}

	/**
	 * 显示删除或添加的对话框
	 */
	private void showAddOrDelDialog(final int musicposition) {
		Builder builder = new Builder(context);
		builder.setTitle("操作")
				.setItems(new String[] { "移出列表", "添加到列表" },
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								switch (which) {
								case 0:
									int musicid = Integer.parseInt(String
											.valueOf(musics.get(musicposition)
													.getId()));
									DBHelper dbHelper = new DBHelper(context);
									dbHelper.removeMusicFromList(currentList,
											musicid);
									Toast.makeText(context, "移出列表成功",
											Toast.LENGTH_SHORT).show();
									// 移除后通知更新
									Intent intent = new Intent();
									intent.setAction(MusicAction.LIST_OPEN);
									intent.putExtra("listID", currentList);
									context.sendBroadcast(intent);
									break;
								case 1:
									showAddDialog(musicposition);
									break;

								default:
									break;
								}
							}
						})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				}).create().show();
		;
	}

	/**
	 * 读取保存的播放记录
	 */
	private void getPlayingMusic() {
		if (myApp.getCurrentlist() == -1) {
			sharedPreferences = context.getSharedPreferences("musicStore",
					Context.MODE_PRIVATE);
			currentMusic = sharedPreferences.getInt("currentMusic", 0);
		} else {
			currentMusic = 0;
		}
	}

	/**
	 * 进入播放页面
	 */
	private void openMusicPlayer() {
		Intent intent = new Intent();
		intent.putExtra("currentMusic", currentMusic);
		intent.putExtra("currentTime", currentTime);
		intent.setClass(context, MusicPlayerActivity.class);
		startActivity(intent);
	}

	/**
	 * 设置当前正在播放的音乐的信息
	 */
	private void setPlayingMusic(int position) {
		playing_title.setText(musics.get(position).getTitle());
		playing_artist.setText(musics.get(position).getArtist());
		playing_duration.setText(String.valueOf(MediaUtils
				.formatDuration(musics.get(position).getDuration())));
	}

	/**
	 * 单击封面进入播放主界面
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.playing_album:
			openMusicPlayer();
			break;
		case R.id.playing_title:
			openMusicPlayer();
			break;
		case R.id.button_play_pause:
			Intent intent = new Intent();
			intent.setAction(MusicAction.MUSIC_SERVICE);
			intent.putExtra("currentMusic", currentMusic);
			switch (myApp.getMplay_status()) {
			case MusicMsg.STATUS_PLAYING:
				intent.putExtra("msg", MusicMsg.PAUSE_MSG);
				break;
			case MusicMsg.STATUS_PAUSE:
				intent.putExtra("msg", MusicMsg.CONTINUE_MSG);
				break;
			case MusicMsg.STATUS_STOP:
				intent.putExtra("msg", MusicMsg.PLAY_MSG);
				break;
			}
			context.startService(intent);
			break;

		}
	}

	@Override
	public void onDestroy() {
		context.unregisterReceiver(mReceiver);
		super.onDestroy();
	}

}
